<template>
  <view class="date-piker">
    <div
      class="text"
      :class="{ placeholder: value === placeholder || value === '' }"
      :style="{ fontSize: fontSize, textAlign: textAlign }"
      @tap="openTimePicker"
    >
      {{ value ? value : placeholder }}
    </div>
    <uni-transition
      :mode-class="['fade']"
      :styles="maskClass"
      :show="mask_show"
      @tip="closeMask"
    />
    <uni-transition
      :duration="500"
      :mode-class="['fade', 'slide-bottom']"
      :styles="transfromClass"
      :show="mask_show"
      @tap="closeMask"
    >
      <view
        class="game-picker-container"
        @tap.stop=""
      >
        <view class="picker-title">
          <view
            class="btn"
            @tap="closeMask"
          >
            取消
          </view>
          <view class="title">
            {{ title }}
          </view>
          <view
            class="btn green"
            @tap="changeTimeValue"
          >
            确定
          </view>
        </view>
        <view class="tips">
          {{ tip }}
        </view>
        <picker-view
          :indicator-style="indicatorStyle"
          class="picker-box"
          :value="time_value"
          @change="toogerTime"
        >
          <picker-view-column
            v-for="(item, index) in fields.split(',')"
            :key="index"
          >
            <view
              v-for="(item1, index1) in list[item - 1]"
              :key="index1"
              class="picker-item"
            >
              {{ item1 }}
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </uni-transition>
  </view>
</template>

<script>
import uniTransition from "./UniTransition";
export default {
	name: "DatePicker",
	components: {
		uniTransition,
	},
	props: {
		// 是否禁用
		disabled: {
			type: Boolean,
			default: false,
		},

		// 占位符
		placeholder: {
			type: String,
			default: "请选择日期时间",
		},

		// 表示有效日期时间范围的开始，
		// 字符串格式为 "YYYY-MM-DD hh:mm:ss"   日期格式必须完整  无关的数据会忽略 比如月日选择器 会忽略 年等其他参数   其他日期参数一样
		start: {
			type: String,
			default: "1970-1-1 00:00",
		},

		// 表示有效日期时间范围的结束
		// 字符串格式为 "YYYY-MM-DD hh:mm:ss"
		end: {
			type: String,
			default: "",
		},

		// 表示选择器的粒度，有效值：year | month | day | hour | minute  分别对应 1,2,3,4,5   不要尝试奇怪组合!  会报错
		fields: {
			type: String,
			default: "1,2,3,4,5",
		},
		title: {
			type: String,
			default: "",
		},
		tip: {
			type: String,
			default: "",
		},
		// 默认值
		// 字符串格式为 "YYYY-MM-DD hh:mm:ss"
		defaultValue: {
			type: String,
			default: "",
		},
		textAlign: {
			type: String,
			default: "left",
		},
		// 因为动态绑定问题不兼容rpx 以下值使用rpx  详情见https://www.jianshu.com/p/97dc7c4a5ebf
		fontSize: {
			type: String,
			default: "30rpx",
		},
	},
	data() {
		return {
			mask_show: false,
			value: "",
			time_value: [],
			list: [[], [], [], [], [], []], // 显示日期数组
			normal_list: [[], [], [], [], []], // 正常日期数组  月 日 时 分 秒
			start_list: [[], [], [], [], []], // 开始日期数组
			end_list: [[], [], [], [], []], // 结束日期数组
			start_time_value: [], // 开始时间格式化数组
			end_time_value: [], // 结束时间格式化数组
			default_time_value: [], // 默认时间格式化数组
		};
	},
	computed: {
		indicatorStyle() {
			return `height: ${Math.round(
				uni.getSystemInfoSync().screenWidth / (750 / 80)
			)}px;`;
		},
		maskClass() {
			return {
				position: "fixed",
				bottom: 0,
				top: 0,
				left: 0,
				right: 0,
				"z-index": 9,
				"background-color": "rgba(0, 0, 0, 0.4)",
			};
		},
		transfromClass() {
			return {
				position: "fixed",
				bottom: 0,
				top: 0,
				left: 0,
				right: 0,
				"z-index": 999,
				/* #ifndef APP-NVUE */
				display: "flex",
				/* #endif */
				"justify-content": "center",
				"align-items": "flex-end",
			};
		},
	},
	watch:{
		start:{
			handler(newVal){
				this.init();
			},
			deep:true,
			immediate:true
		},
		defaultValue:{
			handler(newVal){
				this.init();
			},
			deep:true,
			immediate:true
		}
	},
	beforeMount() {
		// 格式化开始时间
		this.init();
	},
	methods: {
		init(){

			//  修复传入时间参数出现变动  组件不重新渲染的问题
			this.start_time_value = [];
			this.end_time_value = [];
			this.default_time_value = [];
			this.time_value = [];
			this.list = [[], [], [], [], [], []];  // 显示日期数组
			this.normal_list = [[], [], [], [], []]; // 正常日期数组  月 日 时 分 秒
			this.start_list = [[], [], [], [], []];  // 开始日期数组
			this.end_list = [[], [], [], [], []];  // 结束日期数组
			this.getTimeValue(this.start, this.start_time_value);
			if (this.end) {
				// console.log('有限制')
				// 格式化结束时间
				this.getTimeValue(this.end, this.end_time_value);
			}
			//  年份数据处理
			if (this.fields.indexOf("1") >= 0) {
				this.yearsFunc();
			} else {
				this.list[0].push(this.start_time_value[0] + "年");
			}
			// 月份数据处理
			if (this.fields.indexOf("2") >= 0) {
				this.mouthFunc();
			} else {
				this.list[1].push(this.start_time_value[1] + "月");
			}
			// 天的数据处理
			if (this.fields.indexOf("3") >= 0) {
				this.dayFunc();
			} else {
				this.list[2].push(this.start_time_value[2] + "日");
			}
			if (this.fields.indexOf("4") >= 0) {
				this.hoursFunc();
			} else {
				this.list[3].push(this.start_time_value[3] + "时");
			}
			if (this.fields.indexOf("5") >= 0) {
				this.minuteFunc();
			} else {
				this.list[4].push(this.start_time_value[4] + "分");
			}
			if (this.fields.indexOf("6") >= 0) {
				this.secondFunc();
			} else {
				this.list[5].push(this.start_time_value[5] + "秒");
			}
			if (this.defaultValue) {
				this.getTimeValue(this.defaultValue, this.default_time_value);
				let filter = this.fields.split(",");
				for (let i in filter) {
					for (let j in this.list[filter[i] * 1 - 1]) {
						if (
							this.list[filter[i] * 1 - 1][j].replace(/[^0-9]/gi, "") ===
            this.default_time_value[filter[i] * 1 - 1]
						) {
							this.time_value[i] = j;
						}
					}
				}
				let max = Math.max(...this.fields.split(","));
				let index; let date;
				let time_Chinese = [];
				for (let i = 0; i < max; i++) {
					index = this.fields.split(",").indexOf(i * 1 + 1 + "");
					date = this.list[i][0];
					if (index > -1) {
						date = this.list[i][this.time_value[index]];
						if (i === 2) {
							date = this.default_time_value[2] + "日";
						}
						if (i === 3) {
							date = " " + date;
						}
						time_Chinese.push(date);
					}
				}
				time_Chinese = time_Chinese.join("");
				this.value = time_Chinese;
			}
		},
		yearsFunc() {
			//  年份数据处理
			this.time_value.push(0);
			if (this.end) {
				// 划分年份区间
				let years = [];
				for (let i = this.start_time_value[0]; i <= this.end_time_value[0]; i++) {
					years.push(i + "年");
				}
				this.list[0] = years;
			} else {
				// 划分年份区间
				let years = [];
				for (let i = 0; i < 5; i++) {
					years.push(this.start_time_value[0] * 1 + i + "年");
				}
				this.list[0] = years;
			}
		},
		mouthFunc() {
			for (let i = 1; i <= 12; i++) {
				this.normal_list[0].push(i + "月");
			}
			this.time_value.push(0);
			// 划分月份区间
			this.start_list[0] = this.normal_list[0].slice(
				this.start_time_value[1] * 1 - 1
			);
			if (this.end) {
				this.end_list[0] = this.normal_list[0].slice(
					0,
					this.end_time_value[1] * 1
				);
				if (this.start_time_value[0] === this.end_time_value[0]) {
					this.start_list[0] = this.normal_list[0].slice(
						this.start_time_value[1] * 1 - 1,
						this.end_time_value[1] * 1
					);
					this.end_list[0] = this.normal_list[0].slice(
						this.start_time_value[1] * 1 - 1,
						this.end_time_value[1] * 1
					);
				}
			}
			this.list[1] = this.start_list[0];
		},
		changeTimeValue() {
			// let map = new Map([[0,'年'],[1,'月',[2,'日'],[3,'时'],[4,'分'],[5,'秒']]])
			let max = Math.max(...this.fields.split(","));
			let index; let date;
			let time = [];
			let time_Chinese = [];
			for (let i = 0; i < max; i++) {
				index = this.fields.split(",").indexOf(i * 1 + 1 + "");
				date = this.list[i][0];
				if (index > -1) {
					date = this.list[i][this.time_value[index]];
					if (i === 3) {
						date = " " + date;
					}
					time_Chinese.push(date);
				}
				time.push(date ? date.replace(/[^0-9]/gi, "") : date);
			}
			time_Chinese = time_Chinese.join("");
			let time_str = time[0] + "-" + time[1] + "-" + time[2] + " ";
			for (let i = 3; i < 6; i++) {
				if (!time[i]) {
					time[i] = "00";
				}
				if (i === 5) {
					time_str += time[i] * 1 < 10 ? "0" + time[i] * 1 : time[i];
				} else {
					time_str += (time[i] * 1 < 10 ? "0" + time[i] * 1 : time[i]) + ":";
				}
			}

			let obj = {
				time_str,
				time,
				time_Chinese,
			};
			this.value = time_Chinese;
			this.$emit("change", obj);
			this.closeMask();
		},
		dayFunc() {
			this.time_value.push(0);
			let Days = this.getMounthDays(
				this.start_time_value[0] +
          "-" +
          this.start_time_value[1] +
          "-" +
          this.start_time_value[2]
			);
			this.start_list[1] = Days.slice(this.start_time_value[2] * 1 - 1);
			if (this.end) {
				Days = this.getMounthDays(
					this.end_time_value[0] +
            "-" +
            this.end_time_value[1] +
            "-" +
            this.end_time_value[2]
				);
				this.end_list[1] = Days.slice(0, this.end_time_value[2] * 1);
				if (
					this.start_time_value[1] === this.end_time_value[1] &&
          this.start_time_value[0] === this.end_time_value[0]
				) {
					this.start_list[1] = Days.slice(
						this.start_time_value[2] * 1 - 1,
						this.end_time_value[2] * 1
					);
					this.end_list[1] = Days.slice(
						this.start_time_value[2] * 1 - 1,
						this.end_time_value[2] * 1
					);
				}
			}
			this.list[2] = this.start_list[1];
		},
		hoursFunc() {
			this.time_value.push(0);
			for (let i = 0; i <= 23; i++) {
				this.normal_list[2].push(i + "时");
			}
			this.start_list[2] = this.normal_list[2].slice(this.start_time_value[3] * 1);
			if (this.end) {
				this.end_list[2] = this.normal_list[2].slice(
					0,
					this.end_time_value[3] * 1 + 1
				);
				if (
					this.start_time_value[1] === this.end_time_value[1] &&
          this.start_time_value[2] === this.end_time_value[2] &&
          this.start_time_value[0] === this.end_time_value[0]
				) {
					this.start_list[2] = this.normal_list[2].slice(
						this.start_time_value[3] * 1,
						this.end_time_value[3] * 1 + 1
					);
					this.end_list[2] = this.normal_list[2].slice(
						this.start_time_value[3] * 1,
						this.end_time_value[3] * 1 + 1
					);
				}
			}
			this.list[3] = this.start_list[2];
		},
		minuteFunc() {
			this.time_value.push(0);
			for (let i = 0; i <= 59; i++) {
				this.normal_list[3].push(i + "分");
			}
			this.start_list[3] = this.normal_list[3].slice(this.start_time_value[4] * 1);
			if (this.end) {
				this.end_list[3] = this.normal_list[3].slice(
					0,
					this.end_time_value[4] * 1 + 1
				);
				if (
					this.start_time_value[1] === this.end_time_value[1] &&
          this.start_time_value[2] === this.end_time_value[2] &&
          this.start_time_value[3] === this.end_time_value[3] &&
          this.start_time_value[0] === this.end_time_value[0]
				) {
					this.start_list[3] = this.normal_list[3].slice(
						this.start_time_value[4] * 1,
						this.end_time_value[4] * 1 + 1
					);
					this.end_list[3] = this.normal_list[3].slice(
						this.start_time_value[4] * 1,
						this.end_time_value[4] * 1 + 1
					);
				}
			}
			this.list[4] = this.start_list[3];
		},
		secondFunc() {
			this.time_value.push(0);
			for (let i = 0; i <= 59; i++) {
				this.normal_list[4].push(i + "秒");
			}
			this.start_list[4] = this.normal_list[4].slice(this.start_time_value[5] * 1);
			if (this.end) {
				this.end_list[4] = this.normal_list[4].slice(
					0,
					this.end_time_value[5] * 1 + 1
				);
				if (
					this.start_time_value[1] === this.end_time_value[1] &&
          this.start_time_value[2] === this.end_time_value[2] &&
          this.start_time_value[3] === this.end_time_value[3] &&
          this.start_time_value[4] === this.end_time_value[4] &&
          this.start_time_value[0] === this.end_time_value[0]
				) {
					this.start_list[4] = this.normal_list[4].slice(
						this.start_time_value[5] * 1,
						this.end_time_value[5] * 1 + 1
					);
					this.end_list[4] = this.normal_list[4].slice(
						this.start_time_value[5] * 1,
						this.end_time_value[5] * 1 + 1
					);
				}
			}
			this.list[5] = this.start_list[4];
		},
		getMounthDays(date) {
			let dt = new Date(date);
			let month = dt.getMonth();
			dt.setMonth(dt.getMonth() + 1);
			dt.setDate(0);
			let daysArray = [];
			for (let i = 1; i <= dt.getDate(); i++) {
				daysArray.push(i + "日");
			}
			return daysArray;
		},
		closeMask() {
			this.mask_show = false;
		},
		openTimePicker() {
			if (!this.disabled) {
				this.mask_show = true;
			}
		},
		getTimeValue(oldValue, newValue) {
			let timeArray = oldValue.split(" ");
			for (let i of timeArray) {
				let symbol = ":";
				if (i.indexOf("-") >= 0) {
					symbol = "-";
				}
				let DateArray = i.split(symbol);
				for (let j of DateArray) {
					newValue.push(j);
				}
			}
		},
		/**
     * 当时间滑动时判断时候是开始时间还是结束时间进行限制
     */
		toogerTime(e) {
			//  获取发生改变的 索引
			let filter = this.fields.split(",").sort();
			let change_index;
			for (let i in e.detail.value) {
				if (this.time_value[i] !== e.detail.value[i]) {
					change_index = i;
				}
			}
			let index; let date;
			let time = [];
			// 根据上面的索引 获取当前选择的完整时间
			for (let j = 0; j < filter[change_index]; j++) {
				index = this.fields.split(",").indexOf(j + 1 + "");
				date = this.list[j][0];
				if (index > -1) {
					date = this.list[j][e.detail.value[index]];
				}
				date = date ? date.replace(/[^0-9]/gi, "") : date;
				date = date*1<10?"0"+date*1:date;
				time.push(date);
			}
			// 与开始时间和结束时间进行匹配   判读是否限制
			let startTime = this.start_time_value
				.slice(0, filter[change_index] * 1)
				.join("-");
			let endTime = this.end_time_value
				.slice(0, filter[change_index] * 1)
				.join("-");
			if (time.join("-") === startTime) {
				this.list[filter[change_index] * 1] = this.start_list[
					filter[change_index] * 1 - 1
				];
			} else if (time.join("-") === endTime) {
				this.list[filter[change_index] * 1] = this.end_list[
					filter[change_index] * 1 - 1
				];
			} else {
				this.list[filter[change_index] * 1] = this.normal_list[
					filter[change_index] * 1 - 1
				];
				let nowTime = time.slice(0, 2);
				if (nowTime.length === 1) {
					index = this.fields.split(",").indexOf("2");
					date = this.list[1][0];
					if (index > -1) {
						date = this.list[1][e.detail.value[index]];
					}
					nowTime.push(date ? date.replace(/[^0-9]/gi, "") : date);
				}
				if(nowTime.join("-") === this.start_time_value.slice(0, 2).join("-")){
					this.list[2] = this.start_list[1];
				}else if(nowTime.join("-") === this.end_time_value.slice(0, 2).join("-")){
					this.list[2] = this.end_list[1];
				}else{
					nowTime.push("1");
					this.list[2] = this.getMounthDays(nowTime.join("-"));
				}

			}
			this.time_value = e.detail.value;
		},
	},
};
</script>

<style scoped lang="scss">
.text {
  //font-size: 30rpx;
  font-family: PingFangSC, PingFangSC-Medium;
  font-weight: 500;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  text-align: right;
  width: 100%;
  height: 100%;
}
.game-picker-container {
  width: 100%;
  height: 560rpx;
  background: rgba(255, 255, 255, 1);
  border-radius: 20rpx 20rpx 0 0;
  z-index: 99;

  .picker-title {
    height: 114rpx;
    width: 100%;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      flex: 1;
      text-align: center;
      font-size: 36rpx;
      font-weight: 500;
      color: rgba(21, 21, 26, 1);
    }

    .btn {
      height: 100%;
      padding: 0 40rpx;
      box-sizing: border-box;
      line-height: 114rpx;
      font-size: 28rpx;
      color: rgba(147, 147, 164, 1);
    }

    .green {
      color: rgba(67, 221, 139, 1);
    }
  }

  .tips {
    text-align: center;
    font-size: 24rpx;
    color: rgba(147, 147, 163, 1);
    line-height: 30rpx;
  }

  .picker-box {
    width: 100%;
    height: 380rpx;
    margin-top: 36rpx;

    .picker-item {
      line-height: 80rpx;
      text-align: center;
      font-size: 36rpx;
      color: rgba(21, 21, 26, 1);
      font-family: PingFangSC, PingFangSC-Medium;
    }
  }
}
.placeholder {
  color: #9d9da3;
}
</style>
